# -*- coding: utf-8 -*-
"""
数据库模型定义

定义问答系统的数据库表结构，支持向量存储和关键词索引。
"""
from sqlalchemy import Column, Integer, String, Text, DateTime, Float, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func
from pgvector.sqlalchemy import Vector
from typing import Dict, Any

Base = declarative_base()

class BaseQARecord:
    """问答记录基类"""
    id = Column(Integer, primary_key=True, autoincrement=True)
    key = Column(String(255), unique=True, nullable=False, index=True)
    question = Column(Text, nullable=False)
    answer = Column(Text, nullable=False)
    keywords = Column(JSON, default=list)
    category = Column(String(100), index=True)
    source = Column(String(100))
    confidence = Column(Float, default=100.0)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 向量字段 - 使用5120维度匹配deepseek-r1:32b模型
    question_vector = Column(Vector(5120))
    answer_vector = Column(Vector(5120))
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'id': self.id,
            'key': self.key,
            'question': self.question,
            'answer': self.answer,
            'keywords': self.keywords or [],
            'category': self.category,
            'source': self.source,
            'confidence': self.confidence,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

# 为每个知识库创建独立的表
class LogicQARecord(Base, BaseQARecord):
    """逻辑推理问答表"""
    __tablename__ = 'logic_qa_records'

class FloodQARecord(Base, BaseQARecord):
    """洪水相关问答表"""
    __tablename__ = 'flood_qa_records'

class AIQARecord(Base, BaseQARecord):
    """AI相关问答表"""
    __tablename__ = 'ai_qa_records'

# 表映射字典
TABLE_MAPPING = {
    'logic_qa': LogicQARecord,
    'flood_qa': FloodQARecord,
    'ai_qa': AIQARecord
}

# 文件到表的映射
FILE_TO_TABLE = {
    'logic_qa.json': 'logic_qa',
    'flood_qa.json': 'flood_qa', 
    'ai_qa.json': 'ai_qa'
}

# 保持向后兼容的原始表
class QARecord(Base, BaseQARecord):
    """原始问答记录表（向后兼容）"""
    __tablename__ = 'qa_records'